Creating entities is similar to the process for creating tables. You can
create an entity by POSTing to the
URL for the table. For example, the following code shows the HTTP
request-response traffic for creating a simple contact. Note that the
properties of the entity are encoded using Atom. You annotate specific
types (such as dates/times) with the right Entity Framework
attribute.
POST /ContactTable HTTP/1.1
x-ms-date: Tue, 21 Apr 2009 06:39:17 GMT
Authorization: SharedKeyLite sriramk:hdSwtwXUeuDrY2LTvsySw8oD0hcCwKpbqeLL4IbaBJs=
Accept: application/atom+xml,application/xml
Accept-Charset: UTF-8
Content-Type: application/atom+xml
Host: sriramk.table.core.windows.net
Content-Length: 719
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<entry xmlns:d=http://schemas.microsoft.com/ado/2007/08/dataservices
xmlns:m=http://schemas.microsoft.com/ado/2007/08/dataservices/metadata
xmlns="http://www.w3.org/2005/Atom">
<title />
<updated>2009-04-21T06:39:17.3098Z</updated>
<author>
<name />
</author>
<id />
<content type="application/xml">
<m:properties>
<d:Address>One Infinite Loop</d:Address>
<d:Name>Steve Jobs</d:Name>
<d:PartitionKey>a844fa27-7ae2-4894-9cc6-dd0dbdcd5ec4</d:PartitionKey>
<d:RowKey m:null="false" />
<d:Timestamp m:type="Edm.DateTime">0001-01-01T00:00:00</d:Timestamp>
</m:properties>
</content>
</entry>
If the entity is created successfully, the server sends down an
HTTP 201 message, an ETag, and a copy of the entity.
Of course, all of this is just ADO.NET Data Services plumbing. In
.NET code, you typically go through the following steps:
Write your data model classes. In this case, you already wrote
these when you created your table.
Create an instance of the DataServiceContext-derived type to which
to add local changes.
Call SaveChanges to upload
changes to the cloud.
Example 1 shows how you can write code
to add an entity to ContactTable.
This produces the same HTTP traffic as shown earlier.
Example 1. Adding an entity
var account = CloudStorageAccount.Parse(ConfigurationSettings.AppSettings ["DataConnectionString"]);
var svc = new TestDataServiceContext(account.TableEndpoint.ToString(), account.Credentials); //We don't need to specify PartitionKey since it is generated for us in Contact //constructor var contact = new Contact(){ Name="Steve Jobs", Address="One Infinite Loop" }; svc.AddObject("ContactTable", contact); svc.SaveChanges();
|
What is happening here under the covers? Think of DataServiceContext as a sync engine. It
accumulates changes on the client, and sends them in one shot to the
server when SaveChanges is called. In
this case, you’re adding an object to a table (entityset), but the same holds true when
you’re updating/deleting entities, too.